﻿var app = angular.module('app', ["ngResource", "ui.router", 'ngSanitize', 'ui.utils', 'infinite-scroll', 'ngTable', 'webStorageModule', 'ngTouch']);
app.run(['$rootScope', '$timeout', '$state', 'WorkContextSrv', 'webStorage', 'UserSrv', '$interval', '$window','$location', function ($rootScope, $timeout, $state, workContextSrv, webStorage, userSrv, $interval, $window,$location) {
    $rootScope.onPreloading = true;
   
    if (!/^(.*)\/$/i.test(location.pathname)) {
        if (location.href.indexOf('#') > -1) {
            location.href = location.href.split('#')[0] + "/#" + location.href.split('#')[1];
        } else {
            location.href = location.href + "/";
        }
    }

    //State change handler
    $rootScope.$on('$stateChangeStart',
        function (event, toState, toParams, fromState, fromParams) {
            if (!/^(.*)\/$/i.test(location.pathname)) {
                event.preventDefault();
            }
            else if (toState.name === 'signin' && workContextSrv.isAuthenticated()) {
                $state.go("home");
            }
            else if (angular.isDefined(toState.authorize) && toState.authorize && !workContextSrv.isAuthenticated()) {
                event.preventDefault();
                angular.element("body").removeClass("hidden-menu");
                $state.go("signin");
            } else {
              
                $rootScope.$broadcast("chagingPage");

                $rootScope.currentPageName = toState.name;

                angular.element(".fadeWhenChange").stop(true).fadeOut(300, function () {
                    angular.element(".pre-loading").stop(true).fadeIn(300, function () {

                    });
                });
                
                //hide sidebar when on device
                if (angular.element($window).width() <= 960) {
                    angular.element('body').removeClass("hidden-menu");
                }
            }
        }
    );

    $rootScope.$on('hidePreloading', function () {
        angular.element(".pre-loading").hide();
        angular.element(".fadeWhenChange").fadeIn();
    });

    $timeout(function () {
        //set up timer for get task count
        $rootScope.$broadcast("getTaskCount", true);
        $interval(function () {
            $rootScope.$broadcast("getTaskCount", true);
        }, 120000);

        //set up timer for get topic count
        $rootScope.$broadcast("getTopicCount", true);
        $interval(function () {
            $rootScope.$broadcast("getTopicCount", false);
        }, 120000);

        //set up timer for get topic count
        //$rootScope.$broadcast("loadUserStat");
        $interval(function () {
            $rootScope.$broadcast("loadUserStat");
        }, 300000);

    }, 2000);

    //$rootScope.onGlobalLoading = true;

    //Get user info if refresh browser
    if (webStorage.get("user") != null) {
        //get user from local storage
        var currentUser = webStorage.get("user");
        //get user from server
        userSrv.getUserByName(currentUser.userName,false).then(function (dt) {
            //set new user info
            workContextSrv.setCurrentUser(dt);
            //get user stat
            userSrv.getUserStats(dt.userName).success(function (dt2) {
                //save user stat to local storage
                webStorage.remove("user.stat");
                webStorage.add("user.stat", dt2);
                $rootScope.onGlobalLoading = false;
            });
        });
    } else {
        //redirect to signin page
        $location.path('/signin');
        $rootScope.onGlobalLoading = false;
    }

    $rootScope.$on("loadUserStat", function () {
        userSrv.getUserStats(webStorage.get("user").userName).success(function (dt2) {
            //save user stat to local storage
            webStorage.remove("user.stat");
            webStorage.add("user.stat", dt2);
            $rootScope.$broadcast("reCountUserStat");
        });
    });

    //Redirect to sign in page
    $rootScope.$on("redirectToSignInPage", function (e, params) {
        $state.go("signin");
    });

    //Loader
    $rootScope.totalCall = 0;
    $rootScope.$on('LOADER:SHOW', function () {
        $rootScope.showLoading = true;
        $rootScope.totalCall = $rootScope.totalCall + 1;
    });
    $rootScope.$on('LOADER:HIDE', function () {
        $rootScope.totalCall = $rootScope.totalCall - 1;
        if ($rootScope.totalCall == 0) {
            $rootScope.showLoading = false;
        }
    });

    var heightBeforeHide = 0;

    function setMinHeight() {
        angular.element("#left-panel").css('min-height', heightBeforeHide + 'px');
        angular.element("body").css('min-height', heightBeforeHide + 'px');
    }

    function resetMinHeight() {
        heightBeforeHide = jQuery(document).height();
        angular.element("#left-panel").css('min-height', '0');
        angular.element("body").css('min-height', '0');
    }

    $rootScope.$on('MODAL:SHOW', function () {
        resetMinHeight();
    });

    $rootScope.$on('MODAL:HIDE', function () {
        setMinHeight();
    });

    $rootScope.$on('reHeight', function () {
        $timeout(function () {
            var isAndroidDefaultBrowser = /linux;\s+u;+/i.test(navigator.userAgent.toLowerCase());
            var addHeight = isAndroidDefaultBrowser ? 250 : 0;
            var setHeight = angular.element('#main').height();

            //menuHeight = $.left_panel.height();

            var windowHeight = angular.element($window).height() - angular.element("#header").height();
            //set height
            if (setHeight > windowHeight) { // if content height exceedes actual window height and menuHeight
                angular.element("#left-panel").css('min-height', setHeight + addHeight + 'px');
                angular.element("body").css('min-height', setHeight + angular.element("#header").height() + addHeight + 'px');
            } else {
                angular.element("#left-panel").css('min-height', windowHeight + addHeight + 'px');
                angular.element("body").css('min-height', windowHeight + addHeight + 'px');
            }
        }, 200);
    });
    
}])
.factory('authHttpResponseInterceptor', ['$q', '$location', function ($q, $location) {
    return {
        response: function (response) {
            if (response.status === 401) {
                //console.log("Response 401");
            }
            return response || $q.when(response);
        },
        responseError: function (rejection) {
            if (rejection.status === 401) {
                $location.path('/signin');
                //$location.path('/login').search('returnTo', $location.path());
            }
            return $q.reject(rejection);
        }
    };
}])
.factory('abortHttpResponseInterceptor', ['$q', '$rootScope', function ($q, $rootScope) {
    return {
        request: function (config) {
            //console.log(config);
            var canceler = $q.defer();
            config.timeout = canceler.promise;
            $rootScope.$on("abortPendingRequest", function () {
                //don't abort html request, header with 'abortable' is false
                if (/(\.html)$/g.test(config.url) || (angular.isDefined(config.headers.Abortable) && config.headers.Abortable === false)) {

                } else {
                    canceler.resolve();
                }
            });
            return config || $q.when(config);
        }
    };
}])
.config(['$httpProvider', function ($httpProvider) {
    //Http Intercpetor to check auth failures for xhr requests
    $httpProvider.interceptors.push('authHttpResponseInterceptor');
    //add abort event to xhr request
    $httpProvider.interceptors.push('abortHttpResponseInterceptor');
}])
.constant('globalConfig', {
    allowedExtension: 'jpg, jpeg , png, rar, zip, doc, docx, xls, xlsx, ppt, pptx, pdf',
    regexAllowedExtension: /(\.|\/)(jpg|jpeg|png|rar|zip|doc|docx|xls|xlsx|ppt|pptx|pdf)$/i,
    regexAllowedImageExtension: /(\.|\/)(jpg|jpeg|png)$/i,
    allowedTaskDocumentExtension: 'xamlx',
    regexAllowedTaskDocumentExtension: /(\.|\/)(xamlx)$/i,
    maxFiles: 3,
    fileSize: 522752,
    imageSize: 522752,
    dateFormat: !angular.isDefined(appConfig) ? 'mm/dd/yy': appConfig.dateFormat,
    momentDateFormat: !angular.isDefined(appConfig) ? 'MM/DD/YYYY' : appConfig.momentDateFormat,
    momentServerDateFormat: !angular.isDefined(appConfig) ? 'YYYY-MM-DD' : appConfig.momentServerDateFormat
})
.service('globalSrv', [function () {

}])
.service('helperSrv', ['globalConfig', function (globalConfig) {
    //get ie version
    function isIe() {
        var myNav = navigator.userAgent.toLowerCase();
        if (/.net(.*?)\;/g.test(myNav) && /rv\:(\d+).*\)/g.test(myNav)) {
            return parseInt(/rv\:(\d+).*\)/g.exec(myNav)[1]);
        }
        return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
    }

    return {
        isIe: isIe,
        convertDateObjectToFormatedString: function (date) {
            return moment(date).format(globalConfig.momentDateFormat);
        },
        convertFormatedStringToDateObject: function (dateString) {
            return moment(dateString, globalConfig.momentDateFormat).toDate();
        },
        convertServerDateToDateObject: function (serverDate) {
            return new Date(serverDate);
        },
        convertDateObjectToServerDate: function (date) {
            return moment(date).format(globalConfig.momentServerDateFormat);
        }
    };
}])
;
